using System;
using PCSComUtils.Common.DS;
using PCSComMaterials.Inventory.DS;
using PCSComUtils.DataAccess;
using PCSComUtils.DataContext;
using System.Linq;
using System.Transactions;

namespace PCSComMaterials.Inventory.BO
{
	public class OpenAndClosePeriodBO
	{
        /// <summary>
        ///     Closes a period.
        /// </summary>
        /// <param name="effectDate">
        ///     Date of the effect.
        /// </param>
        /// <param name="voPeriod">
        ///     The period value object
        /// </param>
        public void ClosePeriod(DateTime effectDate, Sys_PeriodVO voPeriod)
		{
            using (var trans = new TransactionScope())
            {
                using (var db = new PCSDataContext(Utils.Instance.ConnectionString))
                {
                    DateTime nextMonth = effectDate.AddMonths(1);
                    DateTime previousMonth = effectDate.AddMonths(-1);
                    db.spClosePeriod(effectDate, nextMonth, previousMonth);
                    var period = db.Sys_Periods.FirstOrDefault(p => p.PeriodID == voPeriod.PeriodID);
                    if (period != null)
                    {
                        period.Activate = false;
                    }
                    // find the next period and active it
                    var nextPeriod = db.Sys_Periods.FirstOrDefault(p => p.FromDate == nextMonth);
                    if (nextPeriod != null)
                    {
                        nextPeriod.Activate = true;
                    }
                    if (db.GetChangeSet().Updates.Count > 0)
                    {
                        db.SubmitChanges();
                    }
                }
                trans.Complete();
            }
		}
	}
}
